package com.zjz.demo.PC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: zjz
 * @Date: 2021/10/08/14:03
 * @Description: A--->B--->C--->A
 * @Target:  生产线操作!!
 */
public class Product2 {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printA();
            }
        },"A").start();


        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printB();
            }
        },"B").start();


        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printC();
            }
        },"C").start();
    }
}





class Data3{  // 资源类 lock

    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    // num为1时A执行,2时B执行,3时C执行
    private int num  = 1;


    public void printA(){
        try {
            // 业务-->判断-->执行-->通知
            lock.lock();
            while (num != 1) {
                // 等待
                conditionA.await();
            }
            System.out.println(Thread.currentThread().getName()+"==>AAAAAAAAAAAAAA");
            // 唤醒,唤醒指定的人
            num =2;
            conditionB.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB(){
        try {
            lock.lock();
            while (num != 2){
                conditionB.await();
            }
            System.out.println(Thread.currentThread().getName()+"==>BBBBBBBBBB");

            num = 3;
            conditionC.signal();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void printC(){

        try {
            lock.lock();
            while (num!=3){
                conditionC.await();
            }
            System.out.println(Thread.currentThread().getName()+"==>BBBBBBBBBB");
            num = 1;
            conditionA.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }



}
